package cn.haoma.base.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import cn.haoma.base.network.ConfigConst;

public class CheckNetUtil {

    public static final int CONNECT_SUCCESS = 1;
    public static final int CONNECT_ERROR = 0;
    public static final int CHECK_ERROR = 2;
    private static Context context;
    private static Handler handler;

    /**
     * 检查硬件网络是否打开，如果已经打开再测试网络（Baidu）是否连接的上，如果可以连接返回1,硬件没有打开网络功能返回2，百度可以访问返回0；
     *
     * @param context
     * @param handler
     */
    public static void isConnectNet(Context context, Handler handler) {
        L.i(ConfigConst.LOG_TAG_SOCKET, "检查网络");
        CheckNetUtil.context = context;
        CheckNetUtil.handler = handler;
        ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            handler.sendEmptyMessage(CHECK_ERROR);
            return;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            handler.sendEmptyMessage(CONNECT_ERROR);
            return;
        } else {
            new AsyncTaskImpl().execute(0);
        }

    }


    private static class AsyncTaskImpl extends AsyncTask<Integer, Void, Boolean> {

        @SuppressWarnings("finally")
        @Override
        protected Boolean doInBackground(Integer... params) {
            URL url;
            Boolean isCon = false;
            try {
                url = new URL("http://www.baidu.com");
                URLConnection conn = url.openConnection();
                // 获取网页数据流
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String read = "";
                if ((read = rd.readLine()) != null) {
                    isCon = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return isCon;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                handler.sendEmptyMessage(CONNECT_SUCCESS);
            } else {
                L.i(ConfigConst.LOG_TAG_SOCKET, "网络不通， 请检查网络设置");
                Toast.makeText(context, "网络不通，请检查网络状态", Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessage(CONNECT_ERROR);
            }

        }

    }


}
